package jobs;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import models.Food;
import models.User;
import models.dao.FoodDAO;
import models.dao.UserDAO;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

import play.jobs.Job;
import play.jobs.On;
import play.libs.Mail;

@On("0 25 09 * * ? ")
public class SendMenuMailJob extends Job {

	static SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");

	@Override
	public void doJob() throws EmailException {

		SimpleEmail email = buildEmail();
		if (email != null) {
			Mail.send(email);
		}
	}

	private SimpleEmail buildEmail() {
		SimpleEmail email = null;
		try {
			String messageBody = buildMessageBody();
			List<User> users = UserDAO.getRegisteredUser();
			if (messageBody != null && messageBody.trim().length() > 0
					&& users != null && users.size() > 0) {
				email = new SimpleEmail();
				email.setFrom("lunchordersystem@sybase.com");
				for (User u : users) {
					email.addTo(u.userName);
				}
				email.setCharset("utf-8");
				email
						.setSubject(sDateFormat.format(new Date())
								+ " Lunch Menu");

				email.setMsg(messageBody);

			}
		} catch (Exception e) {
			email = null;
		}
		return email;

	}

	private String buildMessageBody() {
		List<Food> foods = FoodDAO.getTodayFoodList();
		if (foods == null || foods.size() <= 0) {
			return null;
		}

		StringBuilder sb = new StringBuilder(
				"\n===========================\n\n");
		sb.append(new Date().toString());
		sb.append("\n");

		for (Food f : foods) {
			sb.append(f.name);
			sb.append("\n");
		}

		sb.append("\n===========================\n\n");
		sb.append("http://wmbob-mms:9000/");
		sb.append("\n===========================\n\n");

		return sb.toString();
	}

}
